<template>
	<view class="container">
		<view class="code_view">
			<view class="code_item_view" v-for="(item, index) in codeList" @click="copyCode(item)">
				<!-- 进度条 -->
				<view class="progress_bar"
					:style="item.progressBarValue <= 5 || item.progressBarValue == 100 ? 'display: none;' : ''">
					<view class="progress_bar_in" :style="`width: ${item.progressBarValue}%;`"></view>
				</view>
				<!-- 遮蔽层 -->
				<!-- <view class="cover_view"></view> -->
				<uni-row>
					<uni-col :span="6">
						<image :src="baseUrl+item.icon" mode=""></image>
					</uni-col>
					<uni-col :span="18">
						<view class="code_hide" v-if="!item.showFlag">
							<view class="title">
								{{ item.type }}
							</view>
							<view class="source">
								数据来源：<text style="">{{ item.source }}</text>
							</view>
							<view class="source">
								时间：<text style="">{{ formatTime(item.receiveTime) }}</text>
							</view>
						</view>
						<uni-transition v-if="item.showFlag" :show="item.showFlag" :duration="2000" class="code_show"
							ref="ani" custom-class="transition" mode-class="fade">
							<view class="code">
								{{ item.code }}
							</view>
						</uni-transition>
					</uni-col>
				</uni-row>
			</view>
		</view>



		<view class="" v-if="codeList == null || codeList.length <= 0" class="nodata">
			<uni-icons type="close" size="50"></uni-icons>
			<uni-title title="这里空空如也,什么也没有..." align="center"></uni-title>
		</view>
	</view>
</template>

<script>
import api from '@/common/apiUtil.js'
export default {
	data() {
		return {
			baseUrl: api.SERVER_BASE,
			codeList: [],
			duration: 2500,
			socketConnected: false,
			socketTask: null,
		}
	},
	onLoad() {
		// 建立websocket链接
		this.connectWebSocket();
	},
	onShow() {
		// 每次进入时只加载一次
		this.getData()
		// setInterval(this.fetchHistoryData, 5000);
	},
	methods: {
		connectWebSocket() {
			// 创建WebSocket连接
			console.log(api.WS_FIND_CODE_LIST, "urls")
			this.socketTask = uni.connectSocket({
				url: api.WS_FIND_CODE_LIST,
				header: {
					"Authorization": uni.getStorageSync("token"),
				},
				success: () => {
					console.log('WebSocket连接成功');
				},
				fail: (error) => {
					console.error('WebSocket连接失败', error);
				},
			});

			// 监听WebSocket连接打开事件
			this.socketTask.onOpen(() => {
				this.socketConnected = true;
				console.log('WebSocket连接已打开');
			});

			// 监听WebSocket消息事件
			this.socketTask.onMessage((res) => {
				console.log('收到服务器内容：' + res.data);
				// 处理接收到的消息
				this.handleMessage(res.data);
			});

			// 监听WebSocket错误事件
			this.socketTask.onError((error) => {
				console.error('WebSocket发生错误', JSON.stringify(error));
			});

			// 监听WebSocket关闭事件
			this.socketTask.onClose(() => {
				this.socketConnected = false;
				console.log('WebSocket连接已关闭');
			});
		},
		sendMessage(message) {
			if (this.socketConnected) {
				this.socketTask.send({
					data: message,
					success: () => {
						console.log('消息发送成功');
					},
					fail: (error) => {
						console.error('消息发送失败', error);
					},
				});
			} else {
				console.error('WebSocket连接未打开');
			}
		},
		handleMessage(data) {
			// 处理接收到的消息
			data = JSON.parse(data)
			console.log('处理消息：', data);
			let found = false;
			this.codeList.forEach((item, index) => {
				if (item.type == data.type && (item.source == data.source || item.source == '暂无数据')) {
					// 使用 Vue 的 $set 方法替换数据
					this.$set(this.codeList, index, data);
					found = true;
				}
			});
			if (!found) {
				// 如果没有找到匹配项，追加数据
				this.codeList.push(data);
			}
		},
		closeWebSocket() {
			if (this.socketConnected) {
				this.socketTask.close({
					success: () => {
						console.log('WebSocket连接已关闭');
					},
					fail: (error) => {
						console.error('关闭WebSocket连接失败', error);
					},
				});
			}
		},
		copyCode(record) {
			if (record.showFlag) {
				return;
			}
			record.showFlag = true;

			record.progressBarValue = 100
			this.startCountdown(record);
			
			if(record.code != '暂无数据'){
				uni.setClipboardData({
					data: record.code,
					success: res => {
						uni.showToast({
							title: '复制成功',
							icon: "none"
						});
					}
				})
			}
			
			setTimeout(() => {
				record.showFlag = false;
				this.clearCountdown(record);
			}, this.duration)
		},
		startCountdown(record) {
			// 清除已有的定时器
			this.clearCountdown(record);

			// 重置进度条值
			record.progressBarValue = 100;

			// 计算每一步的时间和减少的值
			const totalSteps = 100; // 总步数
			const stepDuration = this.duration / totalSteps;
			const decrementValue = record.progressBarValue / totalSteps;

			console.log(stepDuration, "stepDuration");
			console.log(decrementValue, "decrementValue");

			// 设置定时器
			record.interval = setInterval(() => {
				if (record.progressBarValue > 0) {
					record.progressBarValue -= decrementValue;
					if (record.progressBarValue < 0) {
						record.progressBarValue = 0;
					}
				} else {
					this.clearCountdown(record);
				}
				console.log(record.progressBarValue, "progressBarValue"); // 日志输出当前值
			}, stepDuration);
		},

		clearCountdown(record) {
			if (record.interval) {
				clearInterval(record.interval);
				record.interval = null;
				console.log("执行定时器清空");
				this.$emit('countdown-finished');
			}
		},
		getData() {
			// 查询验证码列表
			this.$get(api.FIND_CODE_LIST).then(res => {
				console.log(res, "codelist-res")
				this.codeList = res.result;
			})
		},
		getLogo(type) {
			const matchLogo = this.logos.find(logo => logo.type === type);
			return matchLogo ? matchLogo.url : '/static/logo.png'; // 如果找到匹配的 logo，则返回相应的素材路径，否则返回空字符串
		},
		open() {
			this.$refs.popup.open()
		},
		close() {
			this.$refs.popup.close()
		},
		confirm(value) {
			console.log(value)
			this.baseUrl = value;
			uni.setStorageSync("baseUrl", value)
			this.$refs.popup.close()
			this.fetchHistoryData();
		},
		onPullDownRefresh() {
			// 下拉刷新
			this.getData();
			uni.stopPullDownRefresh();
		},
		formatTime(time) {
			if(time == null || time == undefined){
				return '暂无数据'
			}
			const now = new Date();
			const date = new Date(time);
			const seconds = Math.floor((now - date) / 1000);

			let interval = Math.floor(seconds / 31536000);
			if (interval >= 1) return `${interval} 年前`;

			interval = Math.floor(seconds / 2592000);
			if (interval >= 1) return `${interval} 个月前`;

			interval = Math.floor(seconds / 86400);
			if (interval >= 1) return `${interval} 天前`;

			interval = Math.floor(seconds / 3600);
			if (interval >= 1) return `${interval} 小时前`;

			interval = Math.floor(seconds / 60);
			if (interval >= 1) return `${interval} 分钟前`;

			return '刚刚';
		},
	}
}
</script>

<style lang="scss">
page {
	background-color: #efefef;
	padding-bottom: 50rpx;
}

/* .container{
		padding-top: 80rpx;
	} */
.nodata {
	text-align: center;
	padding: 100rpx 0;
}

.code_view {
	padding: 20rpx;

	.code_item_view {
		background-color: #fff;
		box-shadow: 10rpx 10rpx 10rpx #ccc;
		margin-bottom: 15rpx;
		border-radius: 20rpx;
		padding: 10rpx 20rpx;
		position: relative;
		overflow: hidden;

		.progress_bar {
			position: absolute;
			bottom: 0;
			left: 0;
			width: 100%;
			height: 5rpx;
			border-radius: 10rpx;

			.progress_bar_in {
				height: 5rpx;
				display: block;
				border-radius: 10rpx;
				background-color: #007aff;
			}
		}

		.cover_view {
			background-color: rgba(0, 0, 0, .5);
			width: 540rpx;
			height: 200rpx;
			position: absolute;
			top: 0;
			right: 0;
			z-index: 9999;
		}

		image {
			width: 150rpx;
			height: 150rpx;
			margin-top: 10rpx;
		}

		.code_hide {
			view {
				margin-bottom: 10rpx;
			}

			.title {
				font-weight: bold;
				margin-top: 15rpx;
			}

			.source {
				font-size: 28rpx;
			}
		}

		.code_show {
			.code {
				font-weight: bold;
				font-size: 80rpx;
				margin-top: 25rpx;
				margin-left: 30rpx;
				letter-spacing: 5rpx;
			}
		}

	}
}
</style>